package com.lagou.rpc.consumer.proxy;

import cn.hutool.core.net.NetUtil;
import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.consumer.client.RpcClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
@Component
@Slf4j
public class RpcClientProxy {

    private List<RpcClient> clients = new ArrayList<>();

    public List<RpcClient> getClients() {
        return clients;
    }
//    static {
//        clients.add(new RpcClient("127.0.0.1", 8897));
//        clients.add(new RpcClient("127.0.0.1", 8898));
//        clients.add(new RpcClient("127.0.0.1", 8899));
//    }

    public static int index = 0;

    public void addClient(String ip, int port) {
        clients.add(new RpcClient(ip, port));
    }

    public void addClient(String ip, int port, String zkPath, long lastResponse, long lastResponseTime) {
        clients.add(new RpcClient(ip,port,zkPath,lastResponse, lastResponseTime));
    }

    public void updateClient(String ip, int port, long lastResponse, long lastResponseTime){
        Optional<RpcClient> first = clients.stream().filter(client -> ip.equals(client.getIp()) && port == client.getPort()).findFirst();
        first.ifPresent(rpcClient -> {
            rpcClient.setLastResponse(lastResponse);
            rpcClient.setLastResponseTime(lastResponseTime);
        });
    }

    public void removeClient(String ip, int port) {
        Optional<RpcClient> first = clients.stream().filter(client -> ip.equals(client.getIp()) && port == client.getPort()).findFirst();
        first.ifPresent(clients::remove);
    }

    private synchronized RpcClient getClient() {
        if (clients.size() == 0) {
            return null;
        }

//        if (index >= clients.size()) {
//            index = 0;
//        }
//        RpcClient rpcClient = clients.get(index % clients.size());
//        // 服务下线删除zookeeper信息有延迟
//        if (!NetUtil.isOpen(new InetSocketAddress(rpcClient.getIp(), rpcClient.getPort()), 200)) {
//            return null;
//        }
//        index++;


        Optional<RpcClient> min = clients.stream().min(Comparator.comparing(RpcClient::getLastResponseTime));
        if (min.isPresent()) {
            RpcClient rpcClient = min.get();
            if (!NetUtil.isOpen(new InetSocketAddress(rpcClient.getIp(), rpcClient.getPort()), 200)) {
                return null;
            }
            return rpcClient;
        } else {
            return null;
        }
    }

    public Object createProxy(Class serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1.封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);
                        //2.创建RpcClient对象
                        RpcClient rpcClient = getClient();
                        if (rpcClient == null) {
                            throw new RuntimeException("client is null");
                        }
                        try {
                            //3.发送消息
                            BigDecimal startTime = new BigDecimal(System.currentTimeMillis());
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            BigDecimal endTime = new BigDecimal(System.currentTimeMillis());
                            long spendTimes = endTime.subtract(startTime).divide(new BigDecimal(1000), RoundingMode.UP).longValue();
                            rpcClient.setLastResponse(spendTimes);
                            rpcClient.setLastResponseTime(endTime.longValue());

                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            log.info("当前RPC-Client：[ip: {}], [port: {}], [结果: {}]",rpcClient.getIp(), rpcClient.getPort(),result.toString());
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e) {
                            throw e;
                        } finally {
//                            rpcClient.close();
                        }

                    }
                });
    }
}
